package com.tmsps.ne4weixin.utils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;
import com.tmsps.ne4weixin.annotation.XStreamFactory;

import cn.hutool.core.util.StrUtil;



/**
 * @Title: XmlUtils.java
 * @Package: com.nuoyun.weixin.util
 * @Description: java对象转XML
 * @author: hanjiefei
 * @date: 2019-10-18
 * @version V1.0
 * @Copyright: 2019
 */
public class XmlUtils {
	
	private static Logger log = LoggerFactory.getLogger(XmlUtils.class);
    private static final XStream xStream = XStreamFactory.getXStream();
    /**
     * 对象转xml
     * @param obj 对象
     * @return
     */
    public static String toXml(Object obj) {
        xStream.processAnnotations(obj.getClass());
        xStream.aliasSystemAttribute(null, "class"); // 去掉 class 属性
        return xStream.toXML(obj);
    }
    /**
     * 解析xml信息
     * @param is
     * @return
     */
    public static Map<String, String> parseRequest(InputStream is) {
		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		try {
			//读取输入流，获取文档对象
			Document document = reader.read(is);
			//根据文档对象获取根节点
			Element root = document.getRootElement();
			//获取根节点的所有的子节点
			List<Element> elements = root.elements();
			for(Element e:elements) {
				map.put(e.getName(), e.getStringValue());
			}
		} catch (DocumentException e) {
			log.error("Exception in parsing message", e);
		}
		log.debug(map.toString());
		return map;
	}
    
    public static Map<String, String> getXmlToMap(String xml) {
		if (StrUtil.isBlank(xml)) {
			log.error("XML PARAMETER ILLEGAL !!!!!!");
			throw new IllegalArgumentException();
		} else {
			return XmlHelper.of(xml.trim()).toLowerCaseMap();
		}
	}
}